package ops.controller;

import java.util.HashMap;
import java.util.Map;

import ops.WindowManager;
import ops.model.EntityAlreadyExistsException;
import ops.model.Term;
import ops.model.manager.EntityController;
import ops.model.manager.TermManager;
import ops.view.TermRegisterPanel;

public class TermController {
	
	private TermManager termManager;

	public TermController() {
		termManager = EntityController.getInstance().getTermManager();
	}
	
	public void add(int year, int semester) {
		Term term = new Term();
		
		term.setYear(year);
		term.setSemester(semester);
		
		try {
			termManager.add(term);
			
			updateTable();
			
			termManager.save();
		} catch (EntityAlreadyExistsException e) {
			e.printStackTrace();
		}
	}
	
	public void updateTable() {
		// TODO
		
		TermRegisterPanel panel = getPanel();
		
		panel.clearTable();
		
		for (Term term : termManager.getMap().values()) {
			panel.addRowToTable(term.getYear(), term.getSemester());
		}
	}
	

	public String getTermNameById(int code) {
		return termManager.getObjectByKey(code).getName();
	}
	
	public Map<String, Object> getTermsList() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		for (Term term : termManager.getMap().values()) {
			map.put(term.getName(), term.getId());
		}
		
		return map;
	}
	
	private TermRegisterPanel getPanel() {
		return (TermRegisterPanel) WindowManager.getInstance().getPanel("register.term");
	}
}
